import time

import pytest
from xkw_UI_auto.PageObjects.bkObjects.login_page import LoginPage
from xkw_UI_auto.PageObjects.bkObjects.home_page import HomePage
from xkw_UI_auto.TestDatas.common.baseData import BaseData as BD
from xkw_UI_auto.TestDatas.loginDatas.login_datas import LoginData as LD
from selenium import webdriver
from datetime import datetime
from py.xml import html


driver = None


@pytest.fixture(scope='class')
def open_browser():
    # 前置条件
    global driver
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(BD.base_url)
    login_page = LoginPage(driver)
    home_page = HomePage(driver)
    yield (driver, login_page, home_page)
    # 后置条件
    driver.quit()


# 首页前置条件
@pytest.fixture(scope='class')
def enter_home():
    global driver
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(BD.base_url)
    login_page = LoginPage(driver)
    home_page = HomePage(driver)
    login_page.login(LD.username, LD.password)
    yield (driver, home_page)
    driver.quit()


@pytest.fixture
def refresh_browser():
    # time.sleep(5)
    yield
    driver.refresh()


def _capture_screenshot():
    return driver.get_screenshot_as_base64()


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候，自动截图，展示到html报告中
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_")+".png"
            screen_img = _capture_screenshot()
            if file_name:
                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra
        report.description = str(item.function.__doc__)


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('Description'))


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(1, html.td(report.description))
